package com.ocom.oauth.auth.replace;

import com.alibaba.fastjson.JSON;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 说明：自定义的获取用户信息
 */
@Service
@Slf4j
public class ReplaceTokenDetailService {

	//获取用户
	public UserDetails load(String token, Long comId) {
		YoCiUser yoCiUser = null;
		Map<String, Object> objectMap = null;
		try {
			objectMap = SecurityUtils.getTokenParse(token);
		} catch (Exception e) {
			throw new InvalidGrantException("token错误");
		}

		Integer exp =  (Integer) objectMap.get("exp");
		Integer courrent = Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000));
		if(exp.compareTo(courrent)<0){
			throw new InvalidGrantException("token过期");
		}

		String userName = (String) objectMap.get("user_name");
		Integer id = (Integer) objectMap.get("id");
		Integer role = (Integer) objectMap.get("role");

//		if (role != 0 && role != 1) {
//			throw new InvalidGrantException("权限不足");
//		}

		List<String> authoritiestring = JSON.parseArray(JSON.toJSONString(objectMap.get("authorities")), String.class);

		List<GrantedAuthority> authorities = new ArrayList<>();
		if(authoritiestring!=null){
			for (String auth : authoritiestring) {
				authorities.add(new SimpleGrantedAuthority(auth));
			}
		}

		Set<String> permissions = new HashSet<>();
		List<String> permissionsArray = JSON.parseArray(JSON.toJSONString(objectMap.get("permissions")), String.class);
		if(permissionsArray!=null){
			for (String auth : permissionsArray) {
				permissions.add(auth);
			}
		}
		if (role != 0 && role != 1) {
			if(!permissions.contains("sys:user:master")){
				throw new InvalidGrantException("权限不足");
			}
		}


		log.info("【管理员登录-超管售后】【oauth】管理员id【{}】管理员【{}】登录单位【{}】",id ,userName,comId);

		return new YoCiUser(id.longValue(),
				comId,
				role.longValue(),
				"0"
				, permissions,
				userName,
				"123456", true, true, true, true, authorities, new ArrayList<>());
	}

}
